package com.qf.order.service.impl;

import com.alibaba.excel.EasyExcel;
import com.qf.base.domain.BaseCustomer;
import com.qf.base.mapper.BaseCustomerMapper;
import com.qf.order.domain.*;
import com.qf.order.domain.dto.OrderExcelDTO;
import com.qf.order.mapper.OrderMapper;
import com.qf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final static String ORDER_ID_PREFIX = "D";

    @Autowired
    private BaseCustomerMapper baseCustomerMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public String requestOrderId() {
        // 获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();

        // 定义格式化器（yyyyMMddHHmm 格式）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");

        // 格式化 LocalDateTime 为字符串
        String preString = localDateTime.format(formatter);
        //查询订单表中最后一条数据的订单编号
        String lastOrderId = orderMapper.selectLastOrderId();
        //如果订单表中有数据，截取订单编号的前10位，与当前时间的前10位进行比较
        if (lastOrderId != null) {
            String lastOrderIdPreString = lastOrderId.substring(0, 10);
            //如果订单表中的最后一条数据的订单编号的前10位与当前时间的前10位不相等，向后拼接0001
            if (!lastOrderIdPreString.equals(preString)) {
                return ORDER_ID_PREFIX + preString + "0001";
            }
            //如果订单表中的最后一条数据的订单编号的前10位与当前时间的前10位相等，向后拼接最后一条数据的订单编号的后四位
            else {
                String lastFour = lastOrderId.substring(lastOrderId.length() - 4);
                int lastFourInt = Integer.parseInt(lastFour);
                lastFourInt++;
                String lastFourStr = String.format("%04d", lastFourInt);
                return ORDER_ID_PREFIX + preString + lastFourStr;
            }
        }
        //如果订单表中没有数据，向后拼接0001
        return ORDER_ID_PREFIX + preString + "0001";

    }

    @Transactional
    @Override
    public void add(OrderVO orderVO) {
        //取出orderVO中的数据
        OrderBasic orderBasic = orderVO.getOrderBasic();
        //获取当前时间
        Date date = new Date();
        orderBasic.setCreateTime(date);
        orderBasic.setOrderStatus("billed");
        OrderRemark orderRemark = orderVO.getOrderRemark();
        List<GoodsInfo> goodsList = orderVO.getGoodsList();
        CostInfo costInfo = orderVO.getCostInfo();
        PaymentMethod paymentMethod = orderVO.getPaymentMethod();
        VehicleRequirement vehicleRequirement = orderVO.getVehicleRequirement();
        //调用orderMapper层添加数据
        orderMapper.addOrderBasic(orderBasic);
        orderMapper.addOrderRemark(orderRemark);
        orderMapper.addGoodsInfo(goodsList);
        orderMapper.addCostInfo(costInfo);
        orderMapper.addPaymentMethod(paymentMethod);
        orderMapper.addVehicleRequirement(vehicleRequirement);
    }

    @Override
    public List<OrderVO> selectOrderList(OrderVO orderVO) {
        //查询订单基础信息表，
        List<OrderBasic> orderBasics = orderMapper.selectOrderBasicList(orderVO);
        //遍历orderBasics订单基础信息表，取出orderId，
        List<List<GoodsInfo>> goodsList = new ArrayList<>();
        //创建存储完整订单信息的集合
        List<OrderVO> OrderVOList = new ArrayList<>();
        orderBasics.forEach(orderBasic -> {
            String orderId = orderBasic.getOrderId();
            // 根据orderId查询订单备注表，
            List<GoodsInfo> goodsInfos = orderMapper.selectGoodsInfo(orderId);
            goodsList.add(goodsInfos);
            // 根据orderId查询成本信息表，
            CostInfo costInfo = orderMapper.selectCostInfo(orderId);
            // 根据orderId查询支付方式表，
            PaymentMethod paymentMethod = orderMapper.selectPaymentMethod(orderId);
            // 根据orderId查询车辆要求表，
            VehicleRequirement vehicleRequirement = orderMapper.selectVehicleRequirement(orderId);
            // 根据orderId查询订单备注表，
            OrderRemark orderRemark = orderMapper.selectOrderRemark(orderId);

            // 将查询到的数据封装到OrderVO对象中，
            OrderVO orderVO1 = new OrderVO();
            orderVO1.setOrderBasic(orderBasic);
            orderVO1.setGoodsList(goodsInfos);
            orderVO1.setCostInfo(costInfo);
            orderVO1.setPaymentMethod(paymentMethod);
            orderVO1.setVehicleRequirement(vehicleRequirement);
            orderVO1.setOrderRemark(orderRemark);

            // 将OrderVO对象添加到OrderVOList集合中，
            OrderVOList.add(orderVO1);
            System.out.println(OrderVOList);

        });
        return OrderVOList;
    }

    @Transactional
    @Override
    public int delOrders(String[] orderIds) {
        orderMapper.delOrderBasic(orderIds);
        orderMapper.delOrderRemark(orderIds);
        orderMapper.delGoodsInfo(orderIds);
        orderMapper.delCostInfo(orderIds);
        orderMapper.delPaymentMethod(orderIds);
        orderMapper.delVehicleRequirement(orderIds);


        if (orderMapper.delOrderBasic(orderIds) == 0 ||
                orderMapper.delOrderRemark(orderIds) == 0 ||
                orderMapper.delGoodsInfo(orderIds) == 0 ||
                orderMapper.delCostInfo(orderIds) == 0 ||
                orderMapper.delPaymentMethod(orderIds) == 0 ||
                orderMapper.delVehicleRequirement(orderIds) == 0) {
            return 0;
        }

        return 1;
    }


    @Transactional
    @Override
    public int update(OrderVO orderVO) {
        //取出orderVO中的数据
        OrderBasic orderBasic = orderVO.getOrderBasic();
        OrderRemark orderRemark = orderVO.getOrderRemark();
        List<GoodsInfo> goodsList = orderVO.getGoodsList();
        List<GoodsInfo> updateGoods = new ArrayList<>();
        List<GoodsInfo> insertGoods = new ArrayList<>();
        //遍历goodsList，判断goodsList中的id是否为空，如果为空，说明是新增的货物信息，需要添加到数据库中
        for (GoodsInfo goodsInfo : goodsList) {
            if (goodsInfo.getId() == null) {
                insertGoods.add(goodsInfo);
            }
            //如果goodsList中的id不为空，说明是修改的货物信息，需要更新到数据库中
            else {
                updateGoods.add(goodsInfo);
            }
        }
        if (!insertGoods.isEmpty()) {
            orderMapper.addGoodsInfo(insertGoods);
        }
        if (!updateGoods.isEmpty()) {
            orderMapper.updateGoodsInfo(updateGoods);
        }





        CostInfo costInfo = orderVO.getCostInfo();
        PaymentMethod paymentMethod = orderVO.getPaymentMethod();
        VehicleRequirement vehicleRequirement = orderVO.getVehicleRequirement();
        //调用orderMapper层更新数据
        int a = orderMapper.updateOrderBasic(orderBasic);
        int b = orderMapper.updateOrderRemark(orderRemark);
        int c = orderMapper.updateCostInfo(costInfo);
        int d = orderMapper.updatePaymentMethod(paymentMethod);
        int e = orderMapper.updateVehicleRequirement(vehicleRequirement);
        if (a == 0 || b == 0 || c == 0 || d == 0 || e == 0) {
            return 0;
        } else {
            return 1;
        }

    }

    @Override
    public OrderVO getOrderInfo(String orderId) {
        //查询订单基础信息表，
        OrderBasic orderBasic = orderMapper.getOrderBasic(orderId);
        //根据orderId查询订单备注表，
        OrderRemark orderRemark = orderMapper.getOrderRemark(orderId);
        //根据orderId查询货物信息表，
        List<GoodsInfo> goodsList = orderMapper.getGoodsList(orderId);
        //根据orderId查询成本信息表，
        CostInfo costInfo = orderMapper .getCostInfo(orderId);
        //根据orderId查询支付方式表，
        PaymentMethod paymentMethod = orderMapper.getPaymentMethod(orderId);
        //根据orderId查询车辆要求表，
        VehicleRequirement vehicleRequirement = orderMapper.getVehicleRequirement(orderId);
        //将查询到的数据封装到OrderVO对象中，
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderBasic(orderBasic);
        orderVO.setOrderRemark(orderRemark);
        orderVO.setGoodsList(goodsList);
        orderVO.setCostInfo(costInfo);
        orderVO.setPaymentMethod(paymentMethod);
        orderVO.setVehicleRequirement(vehicleRequirement);



        return orderVO;
    }

    @Override
    public int delGoods(GoodsInfo goodsInfo) {
        return orderMapper.delGoods(goodsInfo);
    }



    /**
     * 导出订单数据（优先按选中ID导出，无选中则按筛选条件）
     */
    public void exportOrders(List<String> orderIds, OrderQueryParams params, HttpServletResponse response) throws Exception {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("订单数据_" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

        // 2. 查询数据（核心逻辑：优先按选中ID查询）
        List<OrderExcelDTO> orderList;
        if (orderIds != null && !orderIds.isEmpty()) {
            // 选中导出：按ID列表查询
            orderList = orderMapper.selectByOrderIds(orderIds);
            log.info("导出选中的订单，共{}条，ID列表：{}", orderList.size(), orderIds);
        } else {
            // 筛选导出：按原有条件查询
            orderList = orderMapper.selectByParams(params);
            log.info("按筛选条件导出订单，共{}条", orderList.size());
        }

        // 3. 写入Excel并返回
        EasyExcel.write(response.getOutputStream(), OrderExcelDTO.class)
                .sheet("订单列表")
                .doWrite(orderList);
    }
    @Override
    @Transactional
    public void batchImport(List<OrderExcelDTO> orderList) {

        System.out.println("后端接收"+orderList);
        // 转换DTO为实体
        List<Order> orders = new ArrayList<>();
        for (OrderExcelDTO dto : orderList) {
            Order order = new Order();
            BeanUtils.copyProperties(dto, order);
            // 计算总费用
            calculateTotalCost(order);
            orders.add(order);
        }
        System.out.println("转换后的实体"+orders);

        // 批量保存到数据库
        if (!orders.isEmpty()) {
            orderMapper.batchInsert(orders);
        }
    }

    @Override
    public Map<String, Object> getOrderPage(OrderQueryParams params) {
        // 计算分页偏移量
        params.setPageNum((params.getPageNum() - 1) * params.getPageSize());

        // 查询数据
        List<Order> orderList = orderMapper.selectPage(params);
        int total = orderMapper.selectCount(params);

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", orderList);
        result.put("total", total);
        return result;
    }

    @Override
    public List<OrderExcelDTO> listAllOrders(OrderQueryParams params) {
        // 不分页查询所有符合条件的数据
        params.setPageNum(0);
        params.setPageSize(Integer.MAX_VALUE);
        return orderMapper.selectByParams(params);
    }



    // 计算总费用
    private void calculateTotalCost(Order order) {
        if (order.getTransportFee() == null) order.setTransportFee(BigDecimal.ZERO);
        if (order.getPackagingFee() == null) order.setPackagingFee(BigDecimal.ZERO);
        if (order.getFuelFee() == null) order.setFuelFee(BigDecimal.ZERO);

        // 总费用 = 运输费 + 包装费 + 燃油费
        BigDecimal total = order.getTransportFee()
                .add(order.getPackagingFee())
                .add(order.getFuelFee());

        order.setTotalCost(total);
    }


    //查询顾客信息
    @Override
    public List<BaseCustomer> customerInfo() {

        return baseCustomerMapper.findCustomerList();
    }


}
